<template>
  <div>
    <span>this is useTimeout {{ data.value.toString() }}</span>
    <el-button :disabled="!data.value" @click="goon">点我</el-button>
    <el-button @click="stop">暂停</el-button>
    <el-button @click="goon">继续</el-button>
    <div>useTimeout就是封装后的Timeout 可以通过抛出函数来启动、暂停和继续</div>
    <div>
      抛出函数ready, start, stop
      可以通过抛出函数来启动、暂停和继续，ready是true或flase，监控它来知道是否跑完
    </div>
    <hr />
    <span>this is useTimeoutFn{{ isPending }} {{ TimeoutFnStr }}</span>
    <el-button @click="fnClick">点我</el-button>
    <el-button @click="fnStopFn">暂停</el-button>
    <el-button @click="fnStartFn">继续</el-button>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》'
import { useTimeout, promiseTimeout, useTimeoutFn } from "@vueuse/core";

export default {
  name: "useTimeout",
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      data: 0,
      TimeoutFnStr: "我是变化对象",
      isPending: true,
      fnStart: {},
      fnStop: {},
      pause: {},
      resume: {},
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    data(e, o) {
      console.log("watch", e, o);
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  async mounted() {
    let me = this;
    me.data = useTimeout(1000);

    const { ready, start, stop } = useTimeout(5000, { controls: true });
    me.data = ready;

    me.pause = stop;

    me.resume = start;

    await promiseTimeout(1200);

    console.log("promiseTimeout", ready.value); // true
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    stop() {
      console.log("this.pause", this.pause);
      this.pause();
    },
    goon() {
      console.log("this.data", this.data);
      this.resume();
    },
    fnClick() {
      let me = this;
      me.TimeoutFnStr = "5秒后变身";
      me.isPending = true;
      let { isPending, start, stop } = useTimeoutFn(() => {
        me.isPending = false;
        console.log("isPending", isPending);
        me.TimeoutFnStr = "我是变化后的的样子";
      }, 5000);
      console.log("isPending", isPending);
      me.fnStart = start;
      me.fnStop = stop;
    },
    fnStartFn() {
      let me = this;
      me.TimeoutFnStr = "5秒后变身";
      me.fnStart();
      let { isPending, start, stop } = useTimeoutFn(() => {
        me.isPending = false;
        console.log("isPending", isPending);
        me.TimeoutFnStr = "我是变化后的的样子";
      }, 5000);
      me.fnStart = start;
      me.fnStop = stop;
    },
    fnStopFn() {
      let me = this;
      me.TimeoutFnStr = "暂停";
      console.log("me.fnStop", me.fnStop);
      me.fnStop();
    },
  },
};
</script>

<style scoped></style>
